/**
 * 用户登录
 */
$(function() {
	$('#btnUserLogin').click(function() {
		let userName = V('userName');
		let userPassword = V('userPassword');
		if (isNull(userName) || isNull(userPassword)) {
			I('errorPrompt').innerHTML = '请输入用户和密码';
			return;
		}
		let isPassVerify = V('isPassVerify');
		if (isPassVerify != 'S') {
			I('errorPrompt').innerHTML = '请拖动滑块完成验证';
			return;
		}
		if (!isNull(sessionStorage.getItem('btnGrabOrder'))) {
			$('#middleMain').css('z-index', 8000);
			$('.loading').show();
			$('#loadingWord').text('正在登录...');
		}
		I('btnUserLogin').innerHTML = '正在登录...';
		iAmLogin(userName,userPassword);
	});
	//此JS在首页也引入了，但是默认不需要初始化图形验证码，只有抢单登录时才需要，
	//所以需要判断是否为登录页面，如果是登录页面就初始化图形验证码
	if (window.location.href.indexOf('userLogin') > 0){
		//初始化图形验证码
		initVerificationCode();
	}

	$('#verifyImgSource').click(function() {
		initVerificationCode();
	});
	$('#verifyImgCut').click(function() {
		initVerificationCode();
	});
    //注册验证码拖动事件
    $('#drag').drag(null, null, initVerificationCode);
});

/**
 * 我要登录
 * @param userName 登录的用户名
 * @param userPassword 登录的密码
 */
function iAmLogin(userName,userPassword) {
	let btnUserLogin = $('#btnUserLogin'),drag = $('#drag'),middleMain = $('#middleMain');
	btnUserLogin.attr("disabled",true);
	let shaObj = new jsSHA("SHA-1", "TEXT");
	shaObj.update(userPassword);
	let hashPassword = shaObj.getHash("HEX");
	$.ajax({
		type : "POST",
		url : '/index/user/toLogin',
		data : {
			userName : userName,
			userPassword : hashPassword,
			dragMoveX: dragMoveX
		},
		dataType : 'json',
		cache : false,
		async: false,
		success : function(result) {
			let msg = '', s = result.status;
			I('errorPrompt').innerHTML = '';
			if ("0" == s) {
				let nickName = result.nickName;
				nickName = isNull(nickName) ? userName : nickName;
				sessionStorage.setItem(SCS_USER_NAME, userName);
				sessionStorage.setItem(SCS_NICK_NAME, nickName);
				sessionStorage.setItem(SCS_USER_PHONE, result.userPhone);
				sessionStorage.setItem(SCS_USER_ID, result.userId);
				$('.index-login').hide();
				let lastRequestUrl = sessionStorage.getItem('lastRequestUrl');
				//如果上一次请求路径不为空，则直接跳转到上一次请求的路径
				if(!isNull(lastRequestUrl)){
					sessionStorage.removeItem('lastRequestUrl');
					window.location.href = lastRequestUrl;
				}else{
					let thisPagePath = window.document.location.href;
					//如果是登录页面，就跳转到首页，否则不跳转
					if (thisPagePath.indexOf('userLogin') > -1) {
						window.location.href = '/';
					}
				}
				
				if (!isNull(sessionStorage.getItem('btnGrabOrder'))) {
					middleMain.css('z-index', 9006);
					//显示用户名，隐藏注册、登录按钮
                    $('.user-register,.index-login,.user-login').hide();
					$('#IamLogout').show();
					let a = document.createElement('a');
					a.href = '/userPages/myServiceOrder.html';
					a.id = 'myUserName';
					a.innerText = nickName;
					I('Myself').appendChild(a);
                    $('#loadingWord').text('登录成功,正在抢单,请稍候...');
					robingServiceOrder();
				}
				let thisUrl = location.href;
				//当前登录操作的是发布页面
				if (thisUrl.indexOf('issueService') > 0){
					setUserLogin(nickName);
					$('#userLogin').hide();
					$('.loading').show();
                    $('#loadingWord').text('正在发布...');
					issueService();
				}
			} else if (s == '1') {
				msg = '用户名或密码不能为空';
			} else if (s == '2' || s == '4') {
				msg = '验证失败，请拖动滑块完成验证';
			} else if (s == '3') {
				msg = '用户名或密码错误';
			} else if (s == '5') {
				msg = '您的账户已被冻结，如有疑问请联系客服';
            } else if (s == '6') {
                msg = '验证已失效，请刷新页面重新登录';
            }
			if ("0" != s) {
				$('.loading,#verifyImgSource').hide();
				middleMain.css('z-index', 9006);
				sessionStorage.removeItem(SCS_USER_NAME);
				initVerificationCode();
				drag.css({'background-color': '#e8e8e8'});
				drag.empty();
				$('#verifyImgDrag').css('left',-10);
				drag.drag();
				$('.drag_text').css('color','black');
				let dragChildrenArray = drag.children();
				for(let g = 0; g < dragChildrenArray.length; g ++){
					let dragChildren = dragChildrenArray[g];
					if(dragChildren.innerText == '验证通过'){
						$(dragChildren).hide();
						break;
					}
				}
				$('.handler_ok_bg').hide();
			}
			btnUserLogin.attr("disabled",false);
			I('btnUserLogin').innerHTML = '登录';
			I('errorPrompt').innerHTML = msg;
		},
		error: function() {
			$('.loading').hide();
			initVerificationCode();
			middleMain.css('z-index', 9006);
			btnUserLogin.attr("disabled",false);
			I('btnUserLogin').innerHTML = '登录';
			I('errorPrompt').innerHTML = '登录失败';
			sessionStorage.removeItem(SCS_USER_NAME);
            $('#verifyImgDrag').css('left', 0);
            //注册验证码拖动事件
			drag.drag(null, null, initVerificationCode);
		}
	});
}
/**
 * 初始化验证码图片信息
 */
function initVerificationCode() {
    $("#verifyImgDrag,#verifyImgSource,.verify-img-cut").css("display", "none");
    $(".verify-img-loading").show();
    let vis = $(".verify-img-source");
    $.ajax({
        type: "POST",
        async: true,
        url: "/index/makeImgVerifyCode?imgname=" + vis.css("background-image"),
        dataType: 'json',
        success: function (result) {
            if (!result) {
                alert('获取图形验证码失败');
                return;
            }
			//设置大图，小图，及其位置
			let verifyImgUrl = '../staticFile/images/';
			vis.css("background-image", "url(" + verifyImgUrl + "sourceVerifyImg/" + result.sourceImgName + ")");
			$(".verify-img-cut").css({
				"background": "url(" + verifyImgUrl + "tempVerifyImg/" + result.bigImgName + ") no-repeat",
				"display": "none"
			});
			$("#verifyImgDrag").css({
				"background": "url(" + verifyImgUrl + "tempVerifyImg/" + result.smallImgName + ") no-repeat",
				"top": result.location_y + "px"
			});
			$(".verify-img-loading").css("display", "none");
			vis.show();
        },
        error: function (errormsg) {
        	alert("当前系统繁忙，请稍候再试");
        }
    });
}